<template>
  <div>

    <Spin v-if="loading" size="large" fix style="z-index:999;" />

    <section class="section" style="height:56px;margin:0;padding:1em;">
      <Row :gutter="8">
        <Col :xs="3" :sm="4" :md="4" :lg="3" :xl="2">
        <Button type="primary" ghost style="width:100%;" @click="toArticleList">
          <Icon type="ios-arrow-back" />
          <span v-if="screenWidth > 575">文章列表</span>
        </Button>
        </Col>
        <Col :xs="17" :sm="10" :md="12" :lg="12" :xl="10">
        <Input v-model.trim="postForm.title" maxlength="100" show-word-limit placeholder="请输入100个字以内的文章标题" style="width:100%;" />
        </Col>
        <Col v-if="screenWidth > 575" :sm="6" :md="5" :lg="3" :xl="3">
        <Select v-model="postForm.code_style" style="width:100%" placeholder="选择编辑器样式">
          <Option v-for="(item, index) in codeStyleList" :key="index" :value="item.label">{{ item.label }}</Option>
        </Select>
        </Col>
        <Col v-if="screenWidth > 992" :lg="3" :xl="3">
        <Button type="success" ghost style="width:100%;" @click="onUoloadContentImages">
          <span v-if="screenWidth > 575">批量上传图片</span>
        </Button>
        </Col>
        <Col :xs="4" :sm="4" :md="3" :lg="3" :xl="{ span: 3, offset: 3 }">
        <Button type="success" style="min-width:100%;" @click="onSubmit">保存</Button>
        </Col>
      </Row>
    </section>

    <div class="mavonEditor" :style="{ height: editorHeight+'px' }">
      <mavon-editor ref="mavonEditor" v-model="postForm.content" font-size="16px" :toolbars-background="toolbarsBackground" :preview-background="previewBackground" :editable="markdownEditable" :code-style="postForm.code_style" :toolbars="markdownOption" :box-shadow="false" style="height:100%;z-index:99;" @change="change" @save="handleUpdate(true)" @fullScreen="fullScreen" @imgAdd="$imgAdd" @imgDel="imgDel" />
    </div>

    <ui-upload-images :show="resourceAddImageModal" @on-visible-change="onChangeImagesModal" @on-export="onExportImages" />

  </div>
</template>

<script>
import {
  storeContent,
  editContent,
  updateContent
} from '@/api/blogContent/content'
import Setting from '@/settings'
import util from '@/libs/util'
import axios from 'axios'

import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

// import UiUploadImages from '@/components/ui/UiUploadImages.vue'

export default {
  name: 'ContentArticleNewMarkdown',
  components: {
    mavonEditor
    // UiUploadImages
  },
  data () {
    return {
      // 指定编辑的资源ID 0.新增 其他.指定的资源ID
      editId: 0,
      // 页面级加载等待
      loading: false,
      // 文章数据
      postForm: {
        title: '',
        content: '',
        content_html: '',
        code_style: 'monokai-sublime', // markdown样式
        editor_type: 'mavoneditor',
        status: 5
      },

      // ######################################################################################################################

      // 工具栏背景颜色
      toolbarsBackground: '#ffffff',
      // 预览框背景颜色
      previewBackground: '#fbfbfb',
      //	输入框为空时默认提示文本
      markdownPlaceholder: '开始编辑吧...',
      // 是否允许编辑
      markdownEditable: true,
      // MarkDown Editor
      markdownOption: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true // 预览
      },
      // markdown样式
      codeStyleList: [
        {
          value: 'monokai-sublime',
          label: 'monokai-sublime'
        },
        {
          value: 'monokai',
          label: 'monokai'
        },
        {
          value: 'docco',
          label: 'docco'
        },
        {
          value: 'github-gist',
          label: 'github-gist'
        },
        {
          value: 'github',
          label: 'github'
        },
        {
          value: 'googlecode',
          label: 'googlecode'
        },
        {
          value: 'mono-blue',
          label: 'mono-blue'
        },
        {
          value: 'agate',
          label: 'agate'
        },
        {
          value: 'androidstudio',
          label: 'androidstudio'
        },
        {
          value: 'arduino-light',
          label: 'arduino-light'
        },
        {
          value: 'arta',
          label: 'arta'
        },
        {
          value: 'ascetic',
          label: 'ascetic'
        },
        {
          value: 'atelier-cave-dark',
          label: 'atelier-cave-dark'
        },
        {
          value: 'atelier-cave-light',
          label: 'atelier-cave-light'
        },
        {
          value: 'atelier-dune-dark',
          label: 'atelier-dune-dark'
        },
        {
          value: 'atelier-dune-light',
          label: 'atelier-dune-light'
        },
        {
          value: 'atelier-estuary-dark',
          label: 'atelier-estuary-dark'
        },
        {
          value: 'atelier-estuary-light',
          label: 'atelier-estuary-light'
        },
        {
          value: 'atelier-forest-dark',
          label: 'atelier-forest-dark'
        },
        {
          value: 'atelier-forest-light',
          label: 'atelier-forest-light'
        },
        {
          value: 'atelier-heath-dark',
          label: 'atelier-heath-dark'
        },
        {
          value: 'atelier-heath-light',
          label: 'atelier-heath-light'
        },
        {
          value: 'atelier-lakeside-dark',
          label: 'atelier-lakeside-dark'
        },
        {
          value: 'atelier-lakeside-light',
          label: 'atelier-lakeside-light'
        },
        {
          value: 'atelier-plateau-dark',
          label: 'atelier-plateau-dark'
        },
        {
          value: 'atelier-plateau-light',
          label: 'atelier-plateau-light'
        },
        {
          value: 'atelier-savanna-dark',
          label: 'atelier-savanna-dark'
        },
        {
          value: 'atelier-savanna-light',
          label: 'atelier-savanna-light'
        },
        {
          value: 'atelier-seaside-dark',
          label: 'atelier-seaside-dark'
        },
        {
          value: 'atelier-seaside-light',
          label: 'atelier-seaside-light'
        },
        {
          value: 'atelier-sulphurpool-dark',
          label: 'atelier-sulphurpool-dark'
        },
        {
          value: 'atelier-sulphurpool-light',
          label: 'atelier-sulphurpool-light'
        },
        {
          value: 'atom-one-dark',
          label: 'atom-one-dark'
        },
        {
          value: 'atom-one-light',
          label: 'atom-one-light'
        },
        {
          value: 'brown-paper',
          label: 'brown-paper'
        },
        {
          value: 'codepen-embed',
          label: 'codepen-embed'
        },
        {
          value: 'color-brewer',
          label: 'color-brewer'
        },
        {
          value: 'darcula',
          label: 'darcula'
        },
        {
          value: 'dark',
          label: 'dark'
        },
        {
          value: 'darkula',
          label: 'darkula'
        },
        {
          value: 'default',
          label: 'default'
        },
        {
          value: 'dracula',
          label: 'dracula'
        },
        {
          value: 'far',
          label: 'far'
        },
        {
          value: 'foundation',
          label: 'foundation'
        },
        {
          value: 'grayscale',
          label: 'grayscale'
        },
        {
          value: 'gruvbox-dark',
          label: 'gruvbox-dark'
        },
        {
          value: 'gruvbox-light',
          label: 'gruvbox-light'
        },
        {
          value: 'hopscotch',
          label: 'hopscotch'
        },
        {
          value: 'hybrid',
          label: 'hybrid'
        },
        {
          value: 'idea',
          label: 'idea'
        },
        {
          value: 'ir-black',
          label: 'ir-black'
        },
        {
          value: 'kimbie.dark',
          label: 'kimbie.dark'
        },
        {
          value: 'kimbie.light',
          label: 'kimbie.light'
        },
        {
          value: 'magula',
          label: 'magula'
        },
        {
          value: 'obsidian',
          label: 'obsidian'
        },
        {
          value: 'ocean',
          label: 'ocean'
        },
        {
          value: 'paraiso-dark',
          label: 'paraiso-dark'
        },
        {
          value: 'paraiso-light',
          label: 'paraiso-light'
        },
        {
          value: 'pojoaque',
          label: 'pojoaque'
        },
        {
          value: 'purebasic',
          label: 'purebasic'
        },
        {
          value: 'qtcreator_dark',
          label: 'qtcreator_dark'
        },
        {
          value: 'qtcreator_light',
          label: 'qtcreator_light'
        },
        {
          value: 'railscasts',
          label: 'railscasts'
        },
        {
          value: 'rainbow',
          label: 'rainbow'
        },
        {
          value: 'routeros',
          label: 'routeros'
        },
        {
          value: 'school-book',
          label: 'school-book'
        },
        {
          value: 'solarized-dark',
          label: 'solarized-dark'
        },
        {
          value: 'solarized-light',
          label: 'solarized-light'
        },
        {
          value: 'sunburst',
          label: 'sunburst'
        },
        {
          value: 'tomorrow-night-blue',
          label: 'tomorrow-night-blue'
        },
        {
          value: 'tomorrow-night-bright',
          label: 'tomorrow-night-bright'
        },
        {
          value: 'tomorrow-night-eighties',
          label: 'tomorrow-night-eighties'
        },
        {
          value: 'tomorrow-night',
          label: 'tomorrow-night'
        },
        {
          value: 'tomorrow',
          label: 'tomorrow'
        },
        {
          value: 'vs',
          label: 'vs'
        },
        {
          value: 'vs2015',
          label: 'vs2015'
        },
        {
          value: 'xcode',
          label: 'xcode'
        },
        {
          value: 'xt256',
          label: 'xt256'
        },
        {
          value: 'zenburn',
          label: 'zenburn'
        }
      ],
      // 编辑器高度
      editorHeight: document.body.clientHeight - 56,
      // 屏幕宽度
      screenWidth: document.body.clientWidth,

      // ######################################################################################################################

      // 添加图片弹窗
      resourceAddImageModal: false
    }
  },
  watch: {
    screenWidth (val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        setTimeout(() => {
          this.timer = false
        }, 400)
      }
    }
  },
  mounted () {
    window.onresize = () => {
      return (this.screenWidth = document.body.clientWidth)
    }
    this.editId = this.$route.params.id ? this.$route.params.id : 0
    if (this.editId) {
      this.getFormData()
    }
  },
  methods: {
    // ######################################################################################################################
    // # 写博客 MarkDown编辑器 保存和编辑 操作方法
    // ######################################################################################################################

    // 读取指定的资源用于编辑
    getFormData () {
      this.loading = true
      editContent(this.editId)
        .then(async (res) => {
          if (res.status === 200) {
            this.postForm = res.data
          } else {
            this.$Notice.error({ title: res.msg })
          }
          this.loading = false
        })
        .catch((res) => {
          this.loading = false
          this.$Notice.error({ title: res.msg })
        })
    },
    // 提交表单
    onSubmit () {
      if (this.postForm.title == '') {
        this.$Message.warning('文章标题不能为空')
        return
      }
      if (this.editId) {
        this.handleUpdate(true)
      } else {
        this.handleStore()
      }
    },
    // 保存新建的资源
    handleStore () {
      this.loading = true
      this.getContentHtml()
      storeContent(this.postForm)
        .then(async (res) => {
          if (res.status === 200) {
            this.$Notice.success({ title: '保存成功' })
            this.$router.push({ path: '/new/markdown/' + res.data.akey })
          } else {
            this.$Message.error(res.msg)
          }
          this.loading = false
        })
        .catch((res) => {
          this.$Message.error(res.msg)
          this.loading = false
        })
    },
    // 保存更新的资源
    handleUpdate (val = false) {
      if (this.editId) {
        this.getContentHtml()
        updateContent(this.editId, this.postForm)
          .then(async (res) => {
            if (res.status === 200) {
              val
                ? this.$Notice.success({ title: '保存成功' })
                : this.$Message.success('保存成功')
            } else {
              this.$Message.error(res.msg)
            }
            this.loading = false
          })
          .catch((res) => {
            this.$Message.error(res.msg)
            this.loading = false
          })
      }
    },

    // ######################################################################################################################
    // # 编辑器操作方法
    // ######################################################################################################################

    // 编辑区发生变化回调
    change (val) {
      clearTimeout(this.editTime)
      this.editTime = setTimeout(() => {
        this.handleUpdate()
      }, 2500)
    },

    // 切换全屏编辑回调
    fullScreen (val) {
      // this.$Message.info(JSON.stringify(val)) // true or false
    },
    // 图片文件添加回调-绑定@imgAdd event
    $imgAdd (pos, $file) {
      var _this = this
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('file', $file)
      axios({
        method: 'post',
        url: `${Setting.apiBaseURL}/file/upload`,
        data: formdata,
        headers: {
          Accept: '*/*',
          'Authori-zation': 'Bearer ' + util.cookies.get('token')
        }
      }).then((response) => {
        const res = response.data
        if (res.status === 200) {
          this.$refs.mavonEditor.$img2Url(pos, res.data.img_url)
        } else {
          this.$Notice.error({ title: res.msg })
        }
      })
    },

    // 图片文件删除回调
    imgDel (val) {
      // let img_url = val[0]
      // this.$Message.info(JSON.stringify(img_url))
    },

    // 跳转到文章列表页
    toArticleList () {
      this.$router.push({ path: '/admin/article/list' })
    },

    getContentHtml () {
      this.postForm.content_html = this.$refs.mavonEditor.d_render
    },

    // ######################################################################################################################
    // # 批量上传图片
    // ######################################################################################################################

    // 批量上传图片 弹窗
    onUoloadContentImages () {
      this.resourceAddImageModal = true
    },
    // 关闭封面图 弹窗
    onChangeImagesModal (res) {
      this.resourceAddImageModal = res
    },
    // 导出封面图弹窗图片
    onExportImages (res) {
      let thisImages = ''
      res.map((item) => {
        let imgUrl
        if (item.crop) { imgUrl = item.img_url + `?x-oss-process=image/crop,x_${item.cropType.x},y_${item.cropType.y},w_${item.cropType.w},h_${item.cropType.h}` } else { imgUrl = item.img_url }
        thisImages += '![' + item.img_title + '](' + imgUrl + ')\n'
      })
      this.postForm.content += '\n\n' + thisImages
    }
  }
}
</script>

<style scoped>
</style>
